package com.redepronik.negosysdis.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@PropertySource("classpath:persistence.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private Environment env;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf()
				.disable()
				.authorizeRequests()
				.antMatchers("/resources/**",
						"/views/seguridad/login/login.jsf")
				.permitAll()
				.antMatchers("/templates/**")
				.access("isAuthenticated()")
				.antMatchers("/javax.faces.resource/**")
				.access("isAuthenticated()")

				.antMatchers("/views/invfac/directorio/cliente.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/directorio/proveedor.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/directorio/reportes.jsf")
				.hasAnyAuthority("ADMI", "REPO")

				.antMatchers("/views/invfac/producto/producto.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/producto/caracteristica.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/producto/grupo.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/producto/unidad.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/producto/codigoBarra.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/producto/reportes.jsf")
				.hasAnyAuthority("ADMI", "REPO")

				.antMatchers("/views/invfac/infraestructura/bodega.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/infraestructura/local.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/infraestructura/reportes.jsf")
				.hasAnyAuthority("ADMI", "REPO")

				.antMatchers("/views/invfac/compra/ingreso.jsf")
				.hasAnyAuthority("BODE")
				.antMatchers("/views/invfac/compra/listadoIngreso.jsf")
				.hasAnyAuthority("ADMI", "BODE")

				.antMatchers("/views/invfac/venta/cotizacion.jsf")
				.hasAnyAuthority("CAJA")
				.antMatchers("/views/invfac/venta/listadoCotizacion.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/pedido.jsf")
				.hasAnyAuthority("CAJA")
				.antMatchers("/views/invfac/venta/listadoPedido.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/factura.jsf")
				.hasAnyAuthority("CAJA")
				.antMatchers("/views/invfac/venta/listadoFactura.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/notaEntrega.jsf")
				.hasAnyAuthority("CAJA")
				.antMatchers("/views/invfac/venta/listadoNotaEntrega.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/listadoDevolucion.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/listadoNotaCredito.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/listadoDevolucionVenta.jsf")
				.hasAnyAuthority("ADMI", "CAJA")
				.antMatchers("/views/invfac/venta/listadoFacturaInterna.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/venta/cobro.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/venta/reportes.jsf")
				.hasAnyAuthority("ADMI", "REPO")

				.antMatchers("/views/invfac/inventario/kardex.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/inventario/inventarioInicial.jsf")
				.hasAnyAuthority("BODE")
				.antMatchers("/views/invfac/inventario/traspasoBodega.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/inventario/bajaInventario.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers(
						"/views/invfac/inventario/listadoBajaInventario.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/inventario/reportes.jsf")
				.hasAnyAuthority("ADMI", "REPO")

				.antMatchers("/views/invfac/credito/credito.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/credito/cobroCredito.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/credito/reportes.jsf")
				.hasAnyAuthority("ADMI", "REPO")

				.antMatchers("/views/invfac/configuracion/banco.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/configuracion/ciudad.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/configuracion/tipoDocumento.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/invfac/configuracion/parametro.jsf")
				.hasAnyAuthority("ADMI")

				.antMatchers("/views/rrhh/persona.jsf").hasAnyAuthority("ADMI")
				.antMatchers("/views/rrhh/nomina/cargo.jsf")
				.hasAnyAuthority("ADMI")
				.antMatchers("/views/rrhh/nomina/empleado.jsf")
				.hasAnyAuthority("ADMI")

				.antMatchers("/views/seguridad/usuario/usuario.jsf")
				.hasAnyAuthority("SEGU")
				.antMatchers("/views/seguridad/usuario/rol.jsf")
				.hasAnyAuthority("SEGU")
				.antMatchers("/views/seguridad/usuario/bitacora.jsf")
				.hasAnyAuthority("SEGU")

				.antMatchers("/views/views/seguridad/login/cambiarClave.jsf")
				.access("isAuthenticated()").and().formLogin()
				.loginPage("/views/seguridad/login/login.jsf")
				.defaultSuccessUrl("/templates/home.jsf").and().logout()
				.logoutUrl("/views/home.jsf")
				.logoutSuccessUrl("/views/seguridad/login/login.jsf")
				.invalidateHttpSession(true).deleteCookies("JSESSIONID").and()
				.sessionManagement().invalidSessionUrl("/index.html")
				.maximumSessions(1);
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
		auth.jdbcAuthentication().dataSource(dataSource())
				.passwordEncoder(new ShaPasswordEncoder(256))
				.usersByUsernameQuery(getUserQuery())
				.authoritiesByUsernameQuery(getAuthoritiesQuery());
	}

	@Bean
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
		dataSource.setUrl(env.getProperty("jdbc.url"));
		dataSource.setUsername(env.getProperty("jdbc.username"));
		dataSource.setPassword(env.getProperty("jdbc.password"));

		return dataSource;
	}

	private String getAuthoritiesQuery() {
		return "select u.login , r.nombre "
				+ "from seguridad.usuario as u, seguridad.rol as r , seguridad.rolusuario as ur "
				+ "where u.usuarioid = ur.usuarioid and r.rolid = ur.rolid and ur.activo=true and u.login = ?";
	}

	private String getUserQuery() {
		return "select login, password, enabled " + "from seguridad.usuario "
				+ "where login = ?";
	}

}
